package com.gviiii.baiduai.util;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 *
 */
public class FileUtil {

    /**
     * @param fileName
     * @return
     */
    public static String getSimpleFileExName(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * @param fileName
     * @return
     */
    public static String getSimpleFileName(String fileName) {
        return fileName.substring(0, fileName.lastIndexOf("."));
    }

    /**
     * @param path
     * @return
     */
    public static String updateFilePath(String path) {
        if (path.endsWith("/")) {
            return path;
        } else {
            return path + "/";
        }
    }

    /**
     * @param pathName
     * @return
     */
    public static String encodeFiles(String pathName) {
        String encode = null;
        try {
            encode = Base64Util.encode(Files.readAllBytes(Paths.get(pathName)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return encode;
    }

    /**
     * @param pathName
     * @return
     */
    public static String getFileDir(String pathName) {
        return pathName.substring(0, pathName.lastIndexOf(File.separator));
    }

    /**
     * @param rootDir
     * @param dirName
     * @return
     */
    public static Path createDir(String rootDir, String dirName) {
        Path directory=null;
        try {
            if (!Files.exists(Paths.get(rootDir, dirName))) {
                directory = Files.createDirectory(Paths.get(rootDir, dirName));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return directory;
    }

    /**
     * @param path
     * @return
     */
    public static boolean exists(Path path){
        if (Files.exists(path)){
            return true;
        }
        return false;
    }
}
